package com.xunwulian.cmpp.client.handler;


import com.xunwulian.cmpp.pdu.ActiveTest;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ActiveThread extends Thread {
    private IoSession session;
    private static final Logger logger = LoggerFactory.getLogger(ActiveThread.class);
    private long heartbeatInterval = 60000;
    private long heartbeatRetry = 3;
    public static long lastActiveTime = 0;

    public ActiveThread(IoSession s) {
        setDaemon(true);
        this.session = s;
        lastActiveTime = System.currentTimeMillis();
    }

    public void run() {
        while (true) {
            long currentTime = System.currentTimeMillis();
            // > 3 min then lost connection
            if ((currentTime - lastActiveTime) > (heartbeatInterval * heartbeatRetry)) {
                logger.info("connection lost!");
                session.close(true);
                break;
            }
            if ((currentTime - lastActiveTime) > heartbeatInterval) {
                logger.info("发送心跳检测，send ActiveTest");
                lastActiveTime = currentTime;
                ActiveTest activeTest = new ActiveTest();

                Date date = new Date();
                Format formatter = new SimpleDateFormat("MMddHHmmss");
                int timeStamp = Integer.valueOf(formatter.format(date));
                activeTest.timeStamp = timeStamp;
                session.write(activeTest);
            }
        }
        try {
            Thread.sleep(heartbeatInterval);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
